<template>
	<div class="system-user-dialog-container">
		<el-dialog v-model="dialog.visible" :title="dataForm.id ? '修改用户' : '新增用户'" :close-on-click-modal="false" draggable>
			<el-form ref="dataFormRef" :model="dataForm" :rules="dataRules" label-width="auto" v-loading="dialog.loading">
				<el-row :gutter="35">
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="账户名称" prop="username">
							<el-input v-model="dataForm.username" placeholder="请输入账户名称" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="账户密码" prop="password">
							<el-input type="password" v-model="dataForm.password" placeholder="请输入账户密码" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="头像" prop="avatar">
							<el-input v-model="dataForm.avatar" placeholder="请输入头像" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="昵称" prop="nickname">
							<el-input v-model="dataForm.nickname" placeholder="请输入昵称" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="姓名" prop="realname">
							<el-input v-model="dataForm.realname" placeholder="请输入姓名" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="性别" prop="sex">
							<el-select v-model="dataForm.sex" placeholder="请选择" clearable>
								<el-option label="男" value="0"></el-option>
								<el-option label="女" value="1"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="生日" prop="birthday">
							<el-date-picker v-model="dataForm.birthday" placeholder="请输入生日" value-format="YYYY-MM-DD" />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="邮箱" prop="email">
							<el-input v-model="dataForm.email" placeholder="请输入邮箱" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="手机号" prop="phone">
							<el-input v-model="dataForm.phone" placeholder="请输入手机号" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="用户描述" prop="description">
							<el-input v-model="dataForm.description" type="textarea" placeholder="请输入用户描述" maxlength="150"></el-input>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button size="default" @click="dialog.visible = false">取 消</el-button>
					<el-button size="default" type="primary" :loading="dialog.loading" @click="onSubmit">{{ dataForm.id ? '修 改' : '新 增' }}</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script lang="ts" name="systemUserForm" setup>
import { reactive, ref, nextTick } from 'vue';
import { rule } from '/@/utils/validate';
import { useUserApi } from '/@/api/system/user';
import { ElMessage } from 'element-plus';

// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);

// 定义变量内容
const dataFormRef = ref();

const dialog = reactive({
	visible: false,
	loading: false,
});

const dataForm = reactive({
	id: '', // id
	username: '', // 账户名称
	password: '' as String | undefined, // 账户密码
	avatar: '', // 用户头像
	nickname: '', // 用户昵称
	realname: '', // 姓名
	sex: '', // 性别
	birthday: '', // 生日
	email: '', // 邮箱
	phone: '' as String | undefined, // 手机号
	status: 0, // 用户状态
	description: '', // 用户描述
});

const dataRules = ref({
	// 用户名校验，不能为空 、长度 5-20、不能和已有数据重复
	username: [
		{ required: true, message: '用户名不能为空', trigger: 'blur' },
		{ min: 6, max: 20, message: '用户名称长度必须介于 6 和 20 之间', trigger: 'blur' },
		{
			validator: (rule: any, value: any, callback: any) => {
				const flag = new RegExp(/^([a-z\d]+?)$/).test(value);
				if (!flag) {
					callback(new Error('用户名支持小写英文、数字'));
				}

				if (dataForm.id) {
					return callback();
				}

				useUserApi()
					.validateUsername(value)
					.then((res) => {
						if (res.code == 200 && res.data == true) {
							callback(new Error('用户名已经存在'));
						} else {
							callback();
						}
					});
			},
			trigger: 'blur',
		},
	],
	password: [
		{ required: true, message: '密码不能为空', trigger: 'blur' },
		{ min: 6, max: 20, message: '用户密码长度必须介于 6 和 20 之间', trigger: 'blur' },
	],
	// 姓名校验，不能为空、只能是中文
	realname: [
		{ required: true, message: '姓名不能为空', trigger: 'blur' },
		{ validator: rule.chinese, trigger: 'blur' },
	],
	// 邮箱校验
	email: [
		// { required: true, message: '邮箱不能为空', trigger: 'blur' },
		{ type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] },
	],
	// 手机号校验，不能为空、新增的时不能重复校验
	phone: [
		{ required: true, message: '手机号不能为空', trigger: 'blur' },
		{ validator: rule.validatePhone, trigger: 'blur' },
		{
			validator: (rule: any, value: any, callback: any) => {
				if (dataForm.id) {
					return callback();
				}

				useUserApi()
					.validatePhone(value)
					.then((res) => {
						if (res.code == 200 && res.data == true) {
							callback(new Error('手机号已经存在'));
						} else {
							callback();
						}
					});
			},
			trigger: 'blur',
		},
	],
});

// 打开弹窗
const openDialog = async (id: string) => {
	// 清空表单，此项需加表单验证才能使用
	nextTick(() => {
		dataFormRef.value?.resetFields();
	});

	dataForm.id = id;
	dialog.visible = true;

	if (id) {
		dialog.loading = true;
		const res = await useUserApi().info(id);
		if (res.code == 200) {
			Object.assign(dataForm, res.data);
			dialog.loading = false;
		} else {
			dialog.loading = false;
			dialog.visible = false;
		}
	}
};

// 提交
const onSubmit = async () => {
	const valid = await dataFormRef.value.validate().catch(() => {});
	if (!valid) return false;

	try {
		dialog.loading = true;
		let res = null;
		if (dataForm.id) {
			res = await useUserApi().edit(dataForm);
		} else {
			res = await useUserApi().add(dataForm);
		}

		if (res.code == 200) {
			ElMessage.success(res?.msg);
		}
		
	} catch (error: any) {
		ElMessage.error(error.message);
	} finally {
		dialog.loading = false;
		dialog.visible = false;
		emit('refresh');
	}
};

// 暴露变量
defineExpose({
	openDialog,
});
</script>
